package com.xenstra.bhavcopydownloader;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.concurrent.Callable;



public class Worker implements Callable<Boolean>{

	private String downloadFolder;
	private String urlToDownload;
		
	
	public Worker(String downloadFolder, String urlToDownload) {
		super();
		this.downloadFolder = downloadFolder;
		this.urlToDownload = urlToDownload;
	}


	@Override
	public Boolean call() throws Exception {
		try{
			System.out.println("Downloading " + urlToDownload);
			URL url = new URL(urlToDownload);
			InputStream inStream = url.openStream();
			FileOutputStream fileOutputStream = new FileOutputStream(downloadFolder + "\\" + getFileName(urlToDownload));
			
			byte[] buffer = new byte[4096];
			int n = - 1;

			while ( (n = inStream.read(buffer)) != -1){
				if (n > 0){
					fileOutputStream.write(buffer, 0, n);
				}
			}
			
			fileOutputStream.close();
			inStream.close();
			System.out.println("Completed " + urlToDownload);
		}catch(Exception e){
			System.out.println(e);
			return Boolean.FALSE;
		}
		return Boolean.TRUE;
	}

	private String getFileName(String url){
		return url.substring(url.lastIndexOf('/') + 1);
	}
}
